package com.xinke.query.web.query.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinke.query.common.annotation.Log;
import com.xinke.query.common.exception.GaoSuQueryException;
import com.xinke.query.common.result.Result;
import com.xinke.query.model.file.IdentificationFile;
import com.xinke.query.model.query.GaoSuInfoQuery;
import com.xinke.query.model.vo.GaoSuInfoVo;
import com.xinke.query.web.query.service.GaoSuInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.Min;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@Tag(name = "管理员查询接口")
@RequestMapping("/datashare/admin")
@Validated//开启参数校验
public class AdminController {

    @Autowired
    private GaoSuInfoService gaosuInfoService;

    //前端管理员分页查询
    @Log("前端管理员分页查询")
    @Operation(summary = "条件分页查询")
    @PostMapping("/list")
    public Result<IPage<GaoSuInfoVo>> listGaoSuInfo(@RequestParam(defaultValue = "1") @Min(1) long current, @RequestParam(defaultValue = "10") @Min(1) long size, GaoSuInfoQuery gaoSuInfoQuery) {
        IPage<GaoSuInfoVo> page = new Page<>(current, size);
        IPage<GaoSuInfoVo> list = gaosuInfoService.pageGaoSuInfoByQuery(page, gaoSuInfoQuery);
        return Result.ok(list);
    }

    //文件下载：身份文件下载
    @Log("前端管理员下载身份文件")
    @Operation(summary = "下载身份文件")
    @GetMapping("/download/identificationFile/{id}")
    public void downloadIdentificationFileById(@PathVariable Long id, HttpServletResponse response) throws IOException {
        IdentificationFile file = gaosuInfoService.downloadFileById(id);
        if (file.getFileName() == null || file.getFileName().equals("")) {
            throw new GaoSuQueryException(500, "文件名称异常");
        }
        // 设置响应头，告诉浏览器这是byte[]类型
        response.setContentType("application/octet-stream");
        // 处理文件名中文问题
        String encodedFileName = URLEncoder.encode(file.getFileName(), StandardCharsets.UTF_8.name())
                .replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);
        response.setContentLength(file.getFileContent().length);

        // 写入文件数据到响应输出流
        try (OutputStream os = response.getOutputStream()) {
            os.write(file.getFileContent());
            os.flush();
        }
    }

    //根据apply_id从文件系统下载结果
    @Log("前端管理员查询result结果")
    @Operation(summary = "根据apply_id和query_type查询result结果")
    @GetMapping("/download/queryFile")
    public ResponseEntity<FileSystemResource> getResultByApplyIdAndQueryId(
            @RequestParam String applyId,
            @RequestParam Integer queryType) {
        //根据目录找到文件
        File zipFile = gaosuInfoService.getResultByApplyIdAndQueryId(applyId, queryType);

        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        //处理文件名
        String fileName = zipFile.getName();
        String encodingFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replace("+", "%20");
        headers.add("Content-Disposition", "attachment; filename=\"" + encodingFileName + "\"");
        headers.add("Content-Type", "application/zip");
        //返回文件资源
        //分块传输
        FileSystemResource resource = new FileSystemResource(zipFile);
        return new ResponseEntity<>(resource, headers, HttpStatus.OK);
    }


//    //文件下载：计算result文件总条数、总批次
//    @Log("计算result批次")
//    @Operation(summary = "计算批次")
//    @GetMapping("/feedbackData/json-file-info/{gaosuInfoId}")
//    public Result<Map<String, Long>> getFileBatchInfo(@PathVariable @Min(1) Long gaosuInfoId) {
//        Map<String, Long> result = gaosuInfoService.getFileBatchInfoById(gaosuInfoId);
//        return Result.ok(result);
//    }
//
//    //文件下载：下载result文件
//    @Log("前端管理员下载result文件")
//    @Operation(summary = "下载result文件")
//    @GetMapping("/feedbackData/result")
//    public void downloadResultFileById(@RequestParam @Min(1) Long gaosuInfoId,//gaosu_info表id
//                                       @RequestParam(defaultValue = "1") @Min(1) Integer batchNum,//批号
//                                       HttpServletResponse response) throws IOException {
//
//        //获取file对象
//        ResultFile file = gaosuInfoService.getQueryFileByIdAndBatchNum(gaosuInfoId, batchNum);
//        //转为json
//        ObjectMapper objectMapper = new ObjectMapper();
//        String fileJson = objectMapper.writeValueAsString(file);
//        byte[] fileBytes = fileJson.getBytes("UTF-8");
//
//        //返回文件
//        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//        response.setHeader(HttpHeaders.CONTENT_ENCODING, "gzip");//压缩
//        String fileName = "data_" + file.getBatchNum() + ".json.gz";
//        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
//        response.setContentLength(fileBytes.length);
//
//        //写入文件到响应输出流
//        try (ServletOutputStream os = response.getOutputStream();
//             GZIPOutputStream gzipOut = new GZIPOutputStream(os)) {
//            gzipOut.write(fileBytes);
//            gzipOut.flush();
//        }
//    }
}
